/**
 * Created by wangkui on 2016/1/26.
 */
var User = require('./../../models/schema/UserSchema.js');
var _ = require('lodash');
var uuid = require('node-uuid');
var async = require('async'),
    url = require("url"),
    user_avatar=require('./user.avatar.js');

// 用户列表
exports.index = function(req, res) {
    var where = {};
    var args=url.parse(req.url,true).query;
    var fields = '-salt -hashedPassword';
    if( args.fields != undefined){
        fields = args.fields.replace(/\,/g,' ');
    }
    User.find(where,fields,function (err, users) {
        if(err) { return handleError(res, err); }
        return res.status(200).jsonp(users);
    });
};

/**
 * 创建或者更新用户
 * 用户类型:local、wechat、weibo、qq、facebook、twitter
 * 更新逻辑：
 * 传入数据结构(社交网络登录):
 * {
 *  provider:'wechat',
 *  profile:{}
 * }
 */
exports.createorupdate = function(req,res)
{
    var userbody = req.body;
    var where = {};

    if(_.has(userbody,'wechat'))
    {
        userbody.wechat = JSON.parse(userbody.wechat);
        where = {'wechat.unionid': userbody.wechat.unionid};
        if(!_.has(userbody.nickname))
        {
            userbody.nickname = userbody.wechat.nickname;
        }
    }
    if(_.has(userbody,'weibo'))
    {
        userbody.weibo = JSON.parse(userbody.weibo);
        where = {'weibo.id': userbody.weibo.id};
        if(!_.has(userbody.nickname))
        {
            userbody.nickname = userbody.weibo.screen_name;
        }
    }
    if(_.has(userbody,'qq'))
    {
        userbody.qq = JSON.parse(userbody.qq);
        where = {'qq.id': userbody.qq.id};
        if(!_.has(userbody.nickname))
        {
            userbody.nickname = userbody.qq.nickname;
        }
    }
    if(_.has(userbody,'facebook'))
    {
        userbody.facebook = JSON.parse(userbody.facebook);
        where = {'facebook.id': userbody.facebook.id};
        if(!_.has(userbody.nickname))
        {
            userbody.nickname = userbody.facebook.nickname;
        }
    }
    if(_.has(userbody,'twitter'))
    {
        userbody.twitter = JSON.parse(userbody.twitter);
        where = {'twitter.id': userbody.twitter.id};
        if(!_.has(userbody.nickname))
        {
            userbody.nickname = userbody.twitter.nickname;
        }
    }
    if(_.has(userbody,'_Id'))
    {
        where = {'_id': userbody._Id};
    }

    async.waterfall([
        //如果用户存在、修改用户
        function(callback) {
            User.findOne(where, function (err, user) {
                if(!user)
                {
                    callback(null,true,null);
                }
                else
                {
                    var updated = _.merge(user,userbody);
                    updated.save(function (err) {
                        callback(err,false,user);
                    });
                }
            });
        },
        //如果用户不存在、新增用户
        function(isnew,userinfo,callback) {
            if(isnew)
            {
                //新增用户，上传用户头像到azure云存储
                var useravatarId = uuid.v1().replace(/-/g,'');
                //微信用户头像上传
                if(!userbody.hasOwnProperty("avatarId") && userbody.hasOwnProperty("wechat"))
                {
                    user_avatar.uploadavatar(useravatarId,userbody.wechat.headimgurl,"wechat",function(err,info){
                        if(!err)
                        {
                            userbody.avatarId = info.avatarId;
                        }
                        User.create(userbody, function(err, user) {
                            callback(err,user);
                        });
                    });
                }
                //QQ用户头像上传
                if(!userbody.hasOwnProperty("avatarId") && userbody.hasOwnProperty("qq"))
                {
                    user_avatar.uploadavatar(useravatarId,userbody.qq.figureurl_qq_2,"qq",function(err,info){
                        if(!err)
                        {
                            userbody.avatarId = info.avatarId;
                        }
                        User.create(userbody, function(err, user) {
                            callback(err,user);
                        });
                    });
                }
                //新浪微博用户头像上传
                if(!userbody.hasOwnProperty("avatarId") && userbody.hasOwnProperty("weibo"))
                {
                    user_avatar.uploadavatar(useravatarId,userbody.weibo.avatar_large,"weibo",function(err,info){
                        if(!err)
                        {
                            userbody.avatarId = info.avatarId;
                        }
                        User.create(userbody, function(err, user) {
                            callback(err,user);
                        });
                    });
                }
            }
            else
            {
                callback(null,userinfo);
            }
        }
    ], function (err, result) {
        res.json(result);
    });
}

// 根据UserId返回一条记录内容
exports.getuserinfo = function(req, res) {
    var userId = req.params.id;
    User.findById(userId,'-salt -hashedPassword', function (err, user) {
        // if (err) return next(err);
        if (err){console.log(err)};
        if (!user) return res.send(401);
        res.json(user);
    });
};